using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;

public class Player : MonoBehaviour
{
    public float speed = 10;
    
    /**武器 */
    public GameObject weapon;
    
    private Rigidbody2D _rigidbody2D;
    private CapsuleCollider2D _capsuleCollider2D;
    private Animator _animator;

    private bool _isDie = false;
    
    private float _x;
    private float _y;
    private static readonly int DieKey = Animator.StringToHash("die");

    // Start is called before the first frame update
    void Start()
    {
        CameraFollow.instance.SetTarget(transform);
        
        _rigidbody2D = GetComponent<Rigidbody2D>();
        _capsuleCollider2D = GetComponent<CapsuleCollider2D>();
        _animator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        if (_isDie)
        {
            return;
        }
        _x = Input.GetAxis("Horizontal");
        _y = Input.GetAxis("Vertical");

        if (_x > 0)
        {
            var scale = transform.localScale;
            _rigidbody2D.transform.localScale = new Vector3(Math.Abs(scale.x), scale.y, scale.z);
            _animator.SetBool("run", true);
        }
        
        if (_x < 0)
        {
            var scale = transform.localScale;
            _rigidbody2D.transform.localScale = new Vector3(-Math.Abs(scale.x), scale.y, scale.z);
            _animator.SetBool("run", true);
        }

        if (_x < 0.001f && _x > -0.001f)
        {
            _animator.SetBool("run", false);
        }

        Run();

        var type = WeaponMgr.instance.GetWeaponType();
        weapon.SetActive(type != GameWeapon.Null);
        
        if (type != GameWeapon.Null)
        {
            weapon.GetComponent<Weapon>().SetType(type);
            if (Input.GetKeyDown(KeyCode.J))
            {
                // 发射子弹
                weapon.GetComponent<Weapon>().Attack();
            }
        }
        
    }

    private void OnCollisionEnter2D(Collision2D other)
    {
        switch(other.gameObject.tag)
        {
            case "Spike": 
            case "Saw": 
            case "Bound": 
            case "SpikedBall":
            case "Bat":
            case "Plant":
            case "Trunk":
            case "EnemyBullet":
                _animator.SetTrigger(DieKey);
                _capsuleCollider2D.enabled = false;
                _rigidbody2D.bodyType = RigidbodyType2D.Static;
                
                _isDie = true;
                Invoke(nameof(Die), 0.5f);
                break;
        }
    }

    /**死亡 */
    private void Die()
    {
        Destroy(gameObject);
        GameController.instance.GameOver();
    }
    
    private void Run()
    {
        Vector3 movement = new Vector3(_x, 0, 0);
        _rigidbody2D.transform.position += movement * speed * Time.deltaTime;
    }
}
